import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { useAuthStore } from '../store/auth';
import router from '../router';

// type ResponseData<T = any> = {
//   code: number;
//   data: T;
//   message?: string;
// };
const apiPrefix = import.meta.env.VITE_HTTP_BASE_URL
const service = axios.create({
  baseURL: apiPrefix,
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore();
    if (authStore.token) {
      config.headers!['Authorization'] = `Bearer ${authStore.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code === 200) {
      return res;
    }

    // 处理业务错误
    if (res.code === 401) {
      window.location.href = '/login';
    }

    return Promise.reject(new Error(res.message || 'Error'));
  },
  (error) => {
    // 处理HTTP错误
    let message = error.message;
    if (error.response) {
      if (error.response.status === 401) {
        router.push('/login')
      }
    }
    console.error(message);
    return Promise.reject(error);
  }
);

// 基础请求方法
export default function request<T = any>(config: AxiosRequestConfig) {
  return service(config).then(res => res as unknown as T);
}

// GET请求封装
export function fetchGet<T = any>(url: string, params?: Record<string, any>, config?: AxiosRequestConfig) {
  return request<T>({
    url,
    method: 'GET',
    params,
    ...config
  });
}

// POST请求封装
export function fetchPost<T = any>(url: string, data?: Record<string, any>, config?: AxiosRequestConfig) {
  return request<T>({
    url,
    method: 'POST',
    data,
    ...config
  });
}